package com.amar.stdlib.dbmanager;

import java.util.ArrayList;
import java.util.Iterator;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;


public class DbManager {  
	/**
     *@author Alessandro Rossi
     */
	SQLiteDatabase myDb;
	DbHelper       myDbHelper;
	Context        myContext;
	public  static String DB_NAME  ="TodoList";
	private static int DB_VERSION = 1;
	private String TAG            = "DBMANAGER";
	public  static  ArrayList<String> arrTable =new ArrayList<String>();
   /**
    * Costruttore dell'helper
    * @param context
    */
	public DbManager(Context ctx) {
		myContext  = ctx;
		myDbHelper = new DbHelper(ctx, DB_NAME, null, DB_VERSION);
	}
	
	/**
     * metodo per l'apertura del db 
     * @return SQLiteDatabase
     */

	public SQLiteDatabase open() throws SQLiteException  {
	  try {
		    myDb=myDbHelper.getWritableDatabase();//lo rendo leggibile/scrivibile
		    myDb.execSQL("PRAGMA foreign_keys=ON;");//ho dovuto attivare il FK per gestire i legami tra le due tabelle
		   // myDb.setForeignKeyConstraintsEnabled(true); richiede liv 16api
		    return myDb;
	      } catch (SQLiteException ex) {
//	    	Log.d(TAG, "Impossibile aprire il DB errore:" + String.valueOf(ex.getMessage()));
	    	  throw new SQLiteException("Impossibile aprire il DB errore:"+ String.valueOf(ex.getMessage()));
	      } 
	}
	
	/**
     * metodo per la chiusra del db 
     */
	public void close(){ 
		myDb.close();//chiudo db
	}
	
	/**
     * metodo per prendere la versione del db
     */
	public long get_db_version() {
	  return myDb.getVersion();
	}
	
    private class DbHelper extends SQLiteOpenHelper { //classe che ci aiuta nella creazione del db

		public DbHelper(Context context, String name, CursorFactory factory,int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase _db) {
			 Iterator<String> itTable = arrTable.iterator();
		        while (itTable.hasNext()) {
		        	_db.execSQL(itTable.next());

		        }
		    }

		@Override
		public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
			Log.d(TAG,"onUpgrade:");
		     _db.execSQL("DROP TABLE IF EXISTS " + "lista");
		     _db.execSQL("DROP TABLE IF EXISTS " + "lista_elementi" );
		     onCreate(_db);
		}

	}
		

}
